package com.sjyp.cms.controller.admin;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.sjyp.cms.model.Column;
import com.sjyp.cms.model.User;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class ColumnController extends BaseController {
    public void index() {
        int pageNumber = this.getParaToInt("pageNumber", 1);
        int pageSize = this.getParaToInt("pageSize", 10);
        String sql = "SELECT " +
                "t_column.id," +
                "t_column.`name`," +
                "t_column.summary," +
                "t_column.imgPath," +
                "t_column.orderNo," +
                "t_column.createDate," +
                "t_column.columnType ";
        String sqlExceptSelect = "FROM t_column";
        Page<Column> columns = Column.dao.paginate(pageNumber, pageSize, sql, sqlExceptSelect);
        this.setAttr("columns", columns);
        this.render("column_list.html");
    }

    public void save() {
        Column column = this.getBean(Column.class,"");
        column.setCreateDate(new Date());
        boolean isSucess = false;
        if (null == column.getId()) {
            isSucess = column.save();
        } else {
            //修改内容时不删除 图片，上传图片是单独的功能 ，上传图片是再删除
            //this.delImg(column.getId());
            isSucess = column.update();
        }
        //保存（或修改）后跳转至通用成功（或失败）页面
        this.setCommon("栏目","column",isSucess);
    }

    public void goSave() {
        Integer id = this.getParaToInt("id",null);
        this.initPage();//设置分页信息
        if (null != id) {
            Column column = Column.dao.findById(id);
            this.setAttr("column", column);
        }
        this.render("column_form.html");
    }

    public void del() {
        Integer id = this.getParaToInt("id",null);
        this.delImg(id);//删除 图片
        boolean isDelSuccess = Column.dao.deleteById(id);
        this.index();
    }

    /**
     * go 至上传栏目图片
     *
     */
    public void goImgForm() {
        this.initPage();
        this.setAttr("id", this.getParaToInt("id"));
        this.render("column_img_form.html");
    }

    /**
     * 保存栏目图片
     */
    public void saveImg() {
        List<UploadFile> files = this.getFiles();
        int id = this.getParaToInt("id");
        final StringBuilder newImgs = new StringBuilder();
        files.forEach(uFile -> {
            File file = uFile.getFile();
            try {
                String fileName = uFile.getFileName();
                //String absolutePath = file.getAbsolutePath();
                //String targetDir = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator)+1);
                String newFileName = String.valueOf(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf("."),fileName.length());
                PropKit.use("app.properties");
                String newFilePath =  PropKit.get("uploadPath") + newFileName;
                FileUtils.moveFile(file,new File(newFilePath));
                newImgs.append(newFileName).append(";");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        //删除旧图片
        this.delImg(id);
        boolean isSuccess = new Column().setImgPath(newImgs.toString()).setId(id).update();
        if (isSuccess) {
            this.renderHtml("{success:true,msg:'上传成功。'}");
        } else {
            this.renderHtml("{success:false,msg:'上传失败。'}");
        }
    }

    private void delImg(Integer id) {
        Column column = Column.dao.findById(id);
        String imgs = column.getImgPath();
        if (StrKit.notBlank(imgs)) {
            String[] imgsArray = imgs.split(";");
            for (String img : imgsArray) {
                PropKit.use("app.properties");
                FileUtils.deleteQuietly(new File(PropKit.get("uploadPath")+img));
            }
        }
    }

}
